package com.syqc.monitor.ui.historyline

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.view.isVisible
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView.OnCalendarSelectListener
import com.syqc.comlib.utils.CalendarUtil
import com.syqc.entity.DayMile
import com.syqc.monitor.R
import com.syqc.monitor.databinding.PopupHistoryLineBinding
import com.syqc.utils.Units

/**
 *@author joker
 *@time   2024/6/17 15:04
 *@desc
 */
class HistoryLinePopup(
    context: Context,
    private val dateListener: (String) -> Unit,
    private val change: (String, String) -> Unit
) :
    PopupWindow() {
    private val binding = PopupHistoryLineBinding.inflate(LayoutInflater.from(context))
    private val yearDesc by lazy { context.getString(R.string.desc_unit_year) }
    private val monthDesc by lazy { context.getString(R.string.desc_unit_month) }
    private val total by lazy { context.getString(R.string.desc_total) }

    //当前年+月
    private val curYM by lazy { CalendarUtil.getCurYM() }
    private var changYM = 0


    init {
        contentView = binding.root
        isClippingEnabled = false //设置是否裁剪内容
        initView()
        isFocusable = true //popupwindow设置焦点
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
        isOutsideTouchable = false //点击外面窗口消失
        width = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的高
    }

    fun initView() {
        binding.calendarView.setWeekStarWithMon()
        val curYear = binding.calendarView.curYear
        val curMonth = binding.calendarView.curMonth
        val curDay = binding.calendarView.curDay
        changYM = curYear * 100 + curMonth
        binding.ivCalendarN.isVisible = false
        binding.tvCalendarTime.text =
            "$curYear $yearDesc $curMonth $monthDesc"

        binding.calendarView.setOnCalendarSelectListener(object : OnCalendarSelectListener {
            override fun onCalendarOutOfRange(calendar: Calendar?) {
            }

            override fun onCalendarSelect(calendar: Calendar, isClick: Boolean) {
                val year = calendar.year
                val month = calendar.month
                val day = calendar.day
                changYM = year * 100 + month
                binding.ivCalendarN.isVisible = changYM < curYM
                val startDay = CalendarUtil.getYMStartDay(year, month)
                val endDay = CalendarUtil.getYMEndDay(year, month)
                change(
                    getYMDStr(year, month, startDay),
                    getYMDStr(
                        year, month, if (month == curMonth && changYM == curYM) {
                            if (endDay < curDay)
                                endDay else curDay
                        } else {
                            endDay
                        }
                    )
                )
                if (isClick) {
                    val date =
                        "${calendar.year}-${if (month < 10) "0$month" else month}-${if (day < 10) "0$day" else day}"
                    dateListener(date)
                    dismiss()
                }
            }

        })
        binding.calendarView.setOnMonthChangeListener { year, month ->
            binding.tvCalendarTime.text = "$year $yearDesc $month $monthDesc"
        }

        binding.ivCalendarCancel.setOnClickListener {
            dismiss()
        }

        binding.ivCalendarP.setOnClickListener {
            binding.calendarView.scrollToPre()
        }

        binding.ivCalendarN.setOnClickListener {
            if (changYM < curYM)
                binding.calendarView.scrollToNext()
        }
    }

    fun getYMDStr(year: Int, month: Int, day: Int): String {
        val nMonth = if (month < 10) "0$month" else "$month"
        val nDay = if (day < 10) "0$day" else "$day"
        return "$year$nMonth$nDay"
    }

    fun setData(mile: DayMile) {
        binding.calendarView.clearSchemeDate()
        val map = HashMap<String, Calendar>()

        mile.list.forEach {
            val year = it.name.substring(0, 4).toInt()
            val month = it.name.substring(5, 7).toInt()

            val day = it.name.substring(8, 10).toInt()
            val mileD = (it.mile).toDouble()

            val calendar = getSchemeCalendar(year, month, day, Math.round(mileD).toString())
            map[calendar.toString()] = calendar
        }
        //此方法在巨大的数据量上不影响遍历性能，推荐使用

        binding.calendarView.setSchemeDate(map)
        binding.tvMileTotal.text = "$total " + Math.round(mile.mile.toDouble())
            .toString() + " ${Units.km}"
    }

    private fun getSchemeCalendar(year: Int, month: Int, day: Int, text: String): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.scheme = text
        return calendar
    }

    fun setCurCalender(year: Int, month: Int, day: Int) {
        binding.calendarView.scrollToCalendar(year, month, day)
    }

}